// ------------------------------------------------------------------------------------------
// Licensed by Interprise Solutions.
// http://www.InterpriseSolutions.com
// For details on this license please visit  the product homepage at the URL above.
// THE ABOVE NOTICE MUST REMAIN INTACT.
// ------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;

namespace InterpriseSuiteEcommerceCommon.InterpriseIntegration.Web
{
    public static class DownloadManager
    {
        private const int BUFFER_SIZE = 1024;

        public static void DownloadFile(HttpContext ctx, Customer thisCustomer, DownloadableItem download)
        {
            if (null == download || !download.IsPhysicalFileExisting())
            {
                HttpResponseHelper.RespondWithFileNotFound(ctx.Response);
            }

            if (!download.IsActive)
            {
                HttpResponseHelper.RespondWithFileNotFound(ctx.Response);
            }

            if (!download.CanBeDownloadedByCustomer(thisCustomer))
            {
                HttpResponseHelper.RespondWithForbidden(ctx.Response);
            }

            ctx.Response.AddHeader("Content-Type", download.ContentType);
            ctx.Response.AddHeader("Content-Length", download.ContentLength.ToString());

            ctx.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", download.FileName));

            string downloadFileName = download.GetPhysicalFilePath();
            ctx.Response.TransmitFile(downloadFileName);

            // increment the number of times the customer has downloaded this item
            download.IncrementCustomerDownload(thisCustomer);

            ctx.Response.End();
        }
    }
}
